/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package genesis.familytree.server.common.security;

import genesis.familytree.server.common.JsonResult;
import genesis.familytree.server.common.utils.Servlets;
import genesis.familytree.server.common.utils.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.io.IOException;

import static genesis.familytree.server.common.utils.CaptchaUtils.PARAM_NAME_DEFAULT_CAPTCHA;

/**
 * 表单验证（包含验证码）过滤类
 *
 * @author ThinkGem
 * @version 2014-5-19
 */
//@Service
public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
    private static final Logger LOG = LoggerFactory.getLogger(FormAuthenticationFilter.class);

    public static final String PARAM_NAME_CAPTCHA = PARAM_NAME_DEFAULT_CAPTCHA;

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        String captcha = getCaptcha(request);

        return new UsernamePasswordToken(username, password, rememberMe, host, captcha);

    }

    public String getCaptcha(ServletRequest request) {
        return request.getParameter(PARAM_NAME_CAPTCHA);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken tk, AuthenticationException e, ServletRequest request, ServletResponse response) {
        UsernamePasswordToken token = (UsernamePasswordToken) tk;

        String result;
        if (e instanceof UnknownAccountException // 账号不存在
                || e instanceof IncorrectCredentialsException //密码不匹配
                ) {
            token.clear();
            result = JsonResult.create().error("用户名或密码不正确").toJson();
        } else if(e.getMessage().startsWith("json:")) {
            result = e.getMessage().substring(5);
        }else {
            token.clear();
            result = JsonResult.create().error().toJson();
        }

        try {
            response.getWriter().write(result);
        } catch (IOException ex) {
            LOG.error(ex.getMessage(), ex);
        }
        return true;
    }
}